<template>
    <div class="member">
        <div class="depart_box">
            <div class="depart_l">
                <el-input
                    v-model="searchName"
                    class="search_name"
                    placeholder="搜索成员、部门"
                    :prefix-icon="Search"
                    :filter-node-method="filterNode" />
                <el-button v-if="isExternal" style="margin-left: 20px" type="text" @click="getDepartList">
                    刷新页面
                </el-button>
                <el-scrollbar height="400px">
                    <el-tree
                        ref="treeRef"
                        :data="depart"
                        node-key="id"
                        :props="defaultProps"
                        default-expand-all
                        :filter-node-method="filterNode">
                        <template #default="{ node, data }">
                            <span v-if="isMember" class="custom-tree-node">
                                <el-tooltip
                                    v-if="data.type == 'user' && !data.authorized && isDisableType === 1"
                                    effect="dark"
                                    content="该员工需要先前往企业微信授权"
                                    placement="top-start">
                                    <el-checkbox
                                        v-model="data.check"
                                        disabled
                                        class="depart_member"
                                        @change="currentChange(data, node)">
                                        <span>
                                            <el-icon class="depart_member_icon">
                                                <user-filled />
                                            </el-icon>
                                            <span>{{ node.label }}</span>
                                        </span>
                                    </el-checkbox>
                                </el-tooltip>
                                <span v-else>
                                    <el-checkbox
                                        v-if="data.type == 'user'"
                                        v-model="data.check"
                                        :disabled="data.disabled || (isNotWxUser && data.is_wx_follow_user == 0)"
                                        class="depart_member"
                                        @change="currentChange(data, node)">
                                        <span>
                                            <el-icon class="depart_member_icon">
                                                <user-filled />
                                            </el-icon>
                                            <span>{{ node.label }}</span>
                                        </span>
                                    </el-checkbox>
                                    <span v-else>
                                        <img class="depart_icon" src="/static/newDepart.png" alt="" />
                                        {{ node.label }}（{{ data.members || 0 }}）
                                    </span>
                                </span>
                            </span>
                            <span v-else class="custom-tree-node">
                                <el-tooltip
                                    v-if="data.type == 'user' && !data.authorized && isDisableType === '1'"
                                    effect="dark"
                                    content="该员工需要先前往企业微信授权"
                                    placement="top-start">
                                    <el-checkbox
                                        v-model="data.check"
                                        class="depart_member"
                                        disabled
                                        @change="currentChange(data, node)">
                                        <span>
                                            <el-icon class="depart_member_icon">
                                                <user-filled />
                                            </el-icon>
                                            <span>{{ node.label }}</span>
                                        </span>
                                    </el-checkbox>
                                </el-tooltip>
                                <span v-else>
                                    <el-checkbox
                                        v-model="data.check"
                                        class="depart_member"
                                        :disabled="data.disabled"
                                        @change="currentChange(data, node)">
                                        <span>
                                            <el-icon v-if="data.type == 'user'" class="depart_member_icon">
                                                <user-filled />
                                            </el-icon>
                                            <img v-else class="depart_icon mr2" src="/static/newDepart.png" alt="" />
                                            <span>{{ node.label }}</span>
                                            <span>{{ data.type == 'user' ? '' : `（${data.members || 0}）` }}</span>
                                        </span>
                                    </el-checkbox>
                                </span>
                            </span>
                        </template>
                    </el-tree>
                </el-scrollbar>
            </div>
            <div class="depart_r">
                <div class="depart_select_title">已选择的员工</div>
                <el-scrollbar height="400px">
                    <div v-for="item in selectedMember" :key="item.id" class="seled_member">
                        <div class="item_member">
                            <el-icon v-if="item.type == 'user'" class="seled_icon">
                                <user-filled />
                            </el-icon>
                            <img v-else class="depart_icon" src="/static/newDepart.png" alt="" />
                            <span class="member_name">{{ item.name }}</span>
                        </div>
                        <el-icon class="remove_icon" @click="removeItem(item)">
                            <close />
                        </el-icon>
                    </div>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, computed } from 'vue';
import { Search, UserFilled } from '@element-plus/icons-vue';
import type { ElTree } from 'element-plus';
import { ElMessage } from 'element-plus';
import { getDepartUser } from '@/api/common';
import { useStore } from '@/store';
import { getSetionId } from '@/utils/utils';
const emit = defineEmits(['submit']);
const store = useStore();
const treeRef = ref<InstanceType<typeof ElTree>>();

const props = defineProps({
    type: Number
});

interface Tree {
    id: number;
    label: string;
    children?: Tree[];
}
interface Depart {
    departVisble: boolean;
    title?: string;
    creaters?: any[];
    isMember?: boolean;
}

// 选中人员新】
const selectedMember = ref([]);
const limit = ref('1'); //1为员工数据源 2 为开启会话存档和联系人权限的员工数据源
const newSelect = ref([]);
const mobile = ref('');
const disabledSelected = ref([]); // 禁用成员
const isDisableType = ref();
// 弹框
const departVisble = ref(false);
// 是否只支持人员信息
const isMember = ref(true);
// 是否只支持人员信息
const title = ref('部门人员信息');
const multiple = ref(true); //多选
const isExternal = ref(false); // 外部联系人
const isNotWxUser = ref(false); //是否绑定企微员工
// const type = computed(() => {
//     return store.getters['content/type'];
// });

// 取消
const cancelHandel = () => {
    // selectedMember.value = []
    const ids = getSetionId('id', newSelect.value);
    selectedMember.value = selectedMember.value.filter((item: any) => !ids.includes(item.id));
    departVisble.value = false;
    isMember.value = true;
    disabledSelected.value = [];
    emit('submit', selectedMember.value);
};
//确定
const submitHandel = () => {
    newSelect.value = [];
    // emit('submit', selectedMember.value)
    departVisble.value = false;
    disabledSelected.value = [];
    isMember.value = true;
    return selectedMember.value;
};
const searchName = ref('');
const defaultProps = {
    children: 'children',
    label: 'name'
};
watch(searchName, val => {
    treeRef.value!.filter(val);
});
watch(
    () => props.type,
    val => {
        isDisableType.value = val;
    },
    { deep: true, immediate: true }
);
const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
};

// 部门左侧树
const depart = ref([]);
// 获取部门员工信息
watchEffect(() => {
    if (departVisble.value) {
        getDepartList();
    }
});
// watch(
//   () => props.type,
//   (val) => {
//     console.log(val, "看")
//     getDepartList()
//   },
//   { deep: true}
// )
// 获取部门成员信息
const getDepartList = async () => {
    const params = {
        department_id: '',
        is_wx_follow_user: -1,
        is_open_session_archive: -1,
        mobile: ''
    };
    limit.value != '1' ? (params.is_open_session_archive = 1) : ''; // 开启会话存档
    isExternal.value ? (params.is_wx_follow_user = 1) : ''; //开启外部联系人
    params.mobile = mobile.value;
    const data: any = await getDepartUser(params);
    const ids = getSetionId('id', selectedMember.value);
    depart.value = filterMember(data, ids);
};
getDepartList();

// 过滤需要的人员信息
const filterMember = (data: any, ids?: any[]) => {
    data = Array.isArray(data) ? data : [data];
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.disabled = disabledSelected.value.includes(item.id);
        if (multiple.value) {
            item.check = ids.includes(item.id);
        } else {
            const ids = getSetionId('id', selectedMember.value);
            item.check = ids.includes(item.id);
        }
        if (item.users && item.users.length > 0) {
            item.members = item.users.length;
            if ((item.children && item.children.length == 0) || !item.children) {
                item.children = item.users;
            } else {
                item.children = [...item.children, ...item.users];
            }
        }
        if (item.children && item.children.length > 0) {
            item.children = filterMember(item.children, ids);
        }

        checkRepeat(item);
        arr.push(item);
    });
    return arr;
};

const currentChange = (data: Tree, node: any) => {
    if (!selectedMember.value) {
        selectedMember.value = [];
    }
    if (selectedMember.value.length >= 10) {
        ElMessage.error('最多选择10人');
        data.check = false;
        return;
    }
    if (isMember.value && data.type == 'user') {
        seletData(data);
    }
    if (data.type == 'department') {
        seletData(data);
    }
};
// 删除选中成员信息
const removeItem = (data: any) => {
    const result = selectedMember.value.filter((item: any) => item.id != data.id);
    selectedMember.value = result;
    depart.value = restoreDepart(data.id, depart.value);
};
const seletData = (item: any) => {
    if (!selectedMember.value) {
        selectedMember.value = [];
    }
    // 多选
    if (multiple.value) {
        if (item.check) {
            selectedMember.value.push(item);
            newSelect.value.push(item);
        } else {
            if (selectedMember.value.length > 0) {
                selectedMember.value = selectedMember.value.filter((data: any) => item.id != data.id);
            }
        }
    } else {
        selectedMember.value = item.check ? [item] : [];

        filterMember(depart.value);
    }
    // 递归查找相同员工
    checkRepeat(item);
};
// 递归查找相同员工，设置相同的check
const checkRepeat = (item: any, data: Array<object> = depart.value) => {
    data.forEach((v: any) => {
        if (v.id === item.id) {
            v.check = item.check;
        }
        if (v.children) {
            return checkRepeat(item, v.children);
        }
    });
};

//打开员工弹窗时，根据右边的数据确定左侧数的选中- val:true
// 删除右侧选中成员 恢复左边
const restoreDepart = (id: any, data: any, val?: any) => {
    const arr: any[] = [];
    data.forEach((item: any) => {
        if (item.id === id) {
            item.check = val ? true : false;
        } else {
            if (item.children && item.children.length > 0) {
                item.children = val ? restoreDepart(id, item.children, true) : restoreDepart(id, item.children);
            }
        }
        arr.push(item);
    });
    return arr;
};
// 左侧树状态设置为false
const clean = (data: any) => {
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = clean(item.children);
        }
        arr.push(item);
    });
    return arr;
};
const leftchecktree = (id?: any) => {
    depart.value = restoreDepart(id, depart.value, true);
};
// 查找部门的成员信息
const restore = (data: any) => {
    const arr: any[] = [];
    data.map((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = restore(item.children);
        }
        arr.push(item);
    });
    return arr;
};
defineExpose({
    departVisble,
    // appDialog,
    title,
    leftchecktree,
    clean,
    depart,
    submitHandel,
    cancelHandel,
    selectedMember,
    removeItem,
    isMember,
    disabledSelected,
    multiple,
    limit,
    mobile,
    isExternal,
    isNotWxUser
});
</script>

<style lang="scss" scoped>
.member {
    // height: 500px;
    .depart_box {
        display: flex;
        .depart_member_icon {
            vertical-align: bottom;
            margin-right: 2px;
        }
        .depart_icon {
            width: 15px;
            vertical-align: middle;
        }
        .mr2 {
            margin-right: 2px;
        }
    }
    .depart_l {
        width: 350px;
        padding-right: 10px;
        border-right: 1px solid #eaeaea;
        .search_name {
            width: 259px;
            margin-bottom: 10px;
        }
        .custom-tree-node {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .is_member {
            // 不可全选样式
            :deep(.el-tree-node) {
                .is-leaf + .el-checkbox .el-checkbox__inner {
                    display: inline-block;
                }
                .el-checkbox .el-checkbox__inner {
                    display: none;
                }
            }
        }
    }
    .depart_r {
        padding: 10px 20px;
        flex: 1;
        .depart_select_title {
            margin-bottom: 20px;
        }
        .seled_member {
            line-height: 30px;
            display: flex;
            font-size: 14px;
            padding: 0 5px;
            align-items: center;
            justify-content: space-between;
            &:hover {
                background-color: rgba(255, 107, 0, 0.0901960784313725);
            }
            .item_member {
                display: flex;
                align-items: center;
                .seled_icon {
                    color: #ff6b00;
                }
            }
            .member_name {
                margin-left: 2px;
            }
            .remove_icon {
                cursor: pointer;
                &:hover {
                    transform: scale(1.23);
                }
            }
        }
        .active {
            background-color: rgba(255, 107, 0, 0.0901960784313725);
        }
    }
}
</style>
